package cn.jonay.pdmreader.core.reader;

import cn.jonay.pdmreader.core.meta.Pdm;
import cn.jonay.pdmreader.core.meta.Reference;
import cn.jonay.pdmreader.core.meta.Table;
import cn.jonay.pdmreader.core.meta.Entity;
import cn.jonay.pdmreader.core.parser.Parser;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.List;


/**
 * 说明
 *
 * @author zhaozhiguo
 * @version 1.0
 * @date 2021/2/8 9:40
 */
public class PdmReader {
    private Parser parser;

    private PdmReader() {
    }

    public static PdmReader read(File pdmFile) {
        PdmReader pdm = new PdmReader();
        try {
            Document document = new SAXReader().read(pdmFile);
            pdm.parser = new Parser(document);
        } catch (DocumentException e) {
            throw new RuntimeException(e);
        }
        return pdm;
    }
    public static PdmReader read(String pdmFile) {
        File file = new File(pdmFile);
        return read(file);
    }

    public Pdm doParse() {
        Pdm pdm = parser.parseEntity("//c:Children/o:Model", Pdm.class);

        Entity entity = parser.parseEntity("//c:DBMS/o:Shortcut", Entity.class);
        pdm.setDbmsName(entity.getName());
        pdm.setDbmsCode(entity.getCode());

        List<Table> tables = parser.parseTables();
        pdm.setTables(tables);

        List<Reference> references = parser.parseReferences();
        pdm.setReferences(references);
        return pdm;
    }
}
